package com.ynkbny.util;

import com.ynkbny.domain.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * ClassName: MyInterceptor
 * Package: com.ynkbny.util
 * Description:
 *
 * @Author 小雄
 * @Create 2024/5/14 15:19
 * @Version 1.0
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取当前登录用户信息
        Session session = SecurityUtils.getSubject().getSession();
        User user = (User) session.getAttribute("user");
        if(user!=null){
            String roleId = user.getRoleId();
            // 根据角色ID进行权限验证
            if (roleId.equals("1") || roleId.equals("4") || roleId.equals("3")) {
                // 将权限验证结果存储在RequestContextHolder中
                Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).setAttribute("user", user, RequestAttributes.SCOPE_REQUEST);
                return true;
            } else {
                // 如果是无效roleId，返回false，拦截请求
                return false;
            }
        }else {
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
